//
//  HSZJLLocationViewC.m
//  OutSystems
//
//  Created by HiPal on 16/1/10.
//
//

#import "HSZJLLocationViewC.h"
#import "HSZJLAnnotation.h"
#import "HSReverseGeocoderManager.h"
#import "MMLocationManager.h"
#import "HSZJLAdressCell.h"
#import <MapKit/MapKit.h>

@interface HSZJLLocationViewC ()<MKMapViewDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,HSReverseGeocoderManagerDelegate>

- (IBAction)cancelClick:(UIButton *)sender;
- (IBAction)sendClick:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UITableView *tabbleView;

@end

@implementation HSZJLLocationViewC
{
    MMLocationManager *_locateManager;
    HSReverseGeocoderManager *_geocoderManager ;
    NSString * _address;
    CLPlacemark * _placemark;
    NSMutableArray *_dataSource;
}

- (IBAction)cancelClick:(UIButton *)sender {
    [self dismissViewC];
}

- (IBAction)sendClick:(UIButton *)sender {
    if (_delegate && [_delegate respondsToSelector:@selector(hsZJLLocationViewCDelegate: address:)]) {
        [_delegate hsZJLLocationViewCDelegate:_placemark address:_address];
    }
    [self dismissViewC];
}

- (void)dismissViewC{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataSource = [NSMutableArray array];
    [_tabbleView registerNib:[UINib nibWithNibName:@"HSZJLAdressCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    [self initLocateManager];
    //对地图添加单击事件，已添加大头针

}

- (void)initLocateManager
{
    
    //定位服务未打开
    if (![CLLocationManager locationServicesEnabled] || ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorized && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined))
    {
        /*@"请打开定位服务，否则无法记录里程,路径在:设置>隐私>定位服务"*/
        [HSCommonUtil showAlertWithTitle:@"提示" message:@"请打开定位服务，否则无法记录里程,路径在:设置>隐私>定位服务"];
        return ;
    }
    
    //检查网络不可用，给出提示
    if (![[OutSystemsAppDelegate instance] isNetworkAvailable]) {
        
        [self showHint:@"网络无法连接"];
        return ;
    }
    
    //如果打开了，就请求GPS
    _locateManager = [MMLocationManager shareLocation];
    [_locateManager getLocationCoordinate:^(CLLocationCoordinate2D locationCorrrdinate) {
        [self loadAnnotationWithCoor:locationCorrrdinate];
    }];
    
    UITapGestureRecognizer *lpress = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(longPressOnMapView:)];
    [self.mapView addGestureRecognizer:lpress];//m_mapView是MKMapView的实例
}

///地图长按事件
- (void)longPressOnMapView:(UIGestureRecognizer*)gestureRecognizer
{
    
    [self.view endEditing:YES];
    //坐标转换
    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
    CLLocationCoordinate2D touchMapCoordinate =
    [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
    
    //添加大头针
    [self loadAnnotationWithCoor:touchMapCoordinate];
}

//加载大头针
- (void)loadAnnotationWithCoor:(CLLocationCoordinate2D)coor
{
    //清除大头针
    NSArray* array = [NSArray arrayWithArray:self.mapView.annotations];
    [self.mapView removeAnnotations:array];
    
    //起始大头针
    [self reloadMapView:coor];
    
    //解析坐标对应的地址
    _geocoderManager = [HSReverseGeocoderManager instance];
    _geocoderManager.delegate = self ;
    
    CLLocation *location = [[CLLocation alloc]initWithLatitude:coor.latitude longitude:coor.longitude];
    if (location ) {
        [_geocoderManager reverseGeocoderWithCoordinate:location];
    }
}


#pragma mark --HSReverseGeocoderManager
- (void)reverseGeocodeLocation:(CLPlacemark *)placemark {
    if (placemark == nil) {
        return;
    }
    NSString * administrativeArea = @"" ;
    NSString * locality = @"" ;
    NSString * subLocality = @"" ;
    NSString * thoroughfare = @"" ;
    if (placemark.administrativeArea) {
        administrativeArea = placemark.administrativeArea ;//省
    }
    if (placemark.locality) {
        locality = placemark.locality ;//市
    }
    if (placemark.subLocality) {
        subLocality = placemark.subLocality ;//区
    }
    if (placemark.thoroughfare) {
        thoroughfare = placemark.thoroughfare ;//街道
    }
    self.searchBar.text = [NSString stringWithFormat:@"%@%@%@%@",administrativeArea,locality,subLocality,thoroughfare];
    _placemark = placemark;
    _address = [NSString stringWithFormat:@"%@%@%@%@",administrativeArea,locality,subLocality,thoroughfare];

    [self reloadMapView:placemark.location.coordinate];
    [_dataSource  removeAllObjects];
    [_dataSource addObject:placemark];
    [_tabbleView reloadData];
}
- (void)geocodeAddressStringS:(NSArray *)placemark {
    if (placemark.count < 1) {
        return;
    }else{
        CLPlacemark *mark = [placemark firstObject];
        [self reloadMapView:mark.location.coordinate];
        _dataSource = [NSMutableArray arrayWithArray:placemark];
        [_tabbleView reloadData];
    }
    
}
#pragma mark --加载大头针
- (void)reloadMapView:(CLLocationCoordinate2D )location{
   
    HSZJLAnnotation * annotation = [[HSZJLAnnotation alloc] init];
    annotation.coordinate = location;
    [self.mapView addAnnotation:annotation];
    
    MKCoordinateSpan span;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;
    MKCoordinateRegion region={location,span};
    [self.mapView setRegion:region animated:YES];
}

#pragma  mark  --searchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.view endEditing:YES];
    NSLog(@"%@",searchBar.text);
    //解析坐标对应的地址
    _geocoderManager = [HSReverseGeocoderManager instance];
    _geocoderManager.delegate = self ;
    [_geocoderManager geocodeAddressString:searchBar.text];
}


#pragma  mark  --tableView  delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    HSZJLAdressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
   
    CLPlacemark *placemark = _dataSource[indexPath.row];
    NSString * administrativeArea = @"" ;
    NSString * locality = @"" ;
    NSString * subLocality = @"" ;
    NSString * thoroughfare = @"" ;
    if (placemark.administrativeArea) {
        administrativeArea = placemark.administrativeArea ;//省
    }
    if (placemark.locality) {
        locality = placemark.locality ;//市
    }
    if (placemark.subLocality) {
        subLocality = placemark.subLocality ;//区
    }
    if (placemark.thoroughfare) {
        thoroughfare = placemark.thoroughfare ;//街道
    }

    cell.titleLabel.text = locality;
    cell.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",administrativeArea,locality,subLocality,thoroughfare];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CLPlacemark *placemark = _dataSource[indexPath.row];
    NSString * administrativeArea = @"" ;
    NSString * locality = @"" ;
    NSString * subLocality = @"" ;
    NSString * thoroughfare = @"" ;
    if (placemark.administrativeArea) {
        administrativeArea = placemark.administrativeArea ;//省
    }
    if (placemark.locality) {
        locality = placemark.locality ;//市
    }
    if (placemark.subLocality) {
        subLocality = placemark.subLocality ;//区
    }
    if (placemark.thoroughfare) {
        thoroughfare = placemark.thoroughfare ;//街道
    }
    _address = [NSString stringWithFormat:@"%@%@%@%@",administrativeArea,locality,subLocality,thoroughfare];
    _placemark = placemark;
    self.searchBar.text = _address;
    [self reloadMapView:placemark.location.coordinate];
    
}
@end
